import React, { useRef, useState, memo } from 'react';
import _ from 'lodash';
import { history } from 'umi';
import { Button, Popconfirm, message } from 'antd';
import { DeleteOutlined, EditOutlined, PlusOutlined, RollbackOutlined } from '@ant-design/icons';
import CommonTable from '@/components/CommonTable';
import DebounceWrapper from '@/components/DebounceWrapper';
import DictItemDialog from './components/dictItemDialog';
import {
  fetchDictChildList,
  deleteDictItemsByIds,
  deleteDictItemById,
} from '@/services/system/dictionary';

const DebounceButton = DebounceWrapper(Button);

export default memo(() => {
  const childTableRef = useRef(null);
  const [dictProperty] = useState(history.location.state?.dictProperty);
  const [dictName] = useState(history.location.state?.dictName);
  const [dictType] = useState(history.location.state?.dictType);
  const [deleteLoading, setDeleteLoading] = useState(false);
  const [deleteLoadingIds, setDeleteLoadingIds] = useState([]);
  const [dictItemModalOptions, setDictItemModalOptions] = useState({});
  const [dictItemModalVisible, setDictItemModalVisible] = useState(false);

  // 切换loading
  const toggleDeleteLoading = (id, status) => {
    setDeleteLoadingIds((list) => {
      const nextList = [...list];
      if (status) {
        nextList.push(id);
      } else {
        const index = _.indexOf(nextList, id);
        if (index > -1) {
          nextList.splice(index, 1);
        }
      }
      return nextList;
    });
  };

  return (
    <>
      <CommonTable
        ref={childTableRef}
        rowKey={'id'}
        indexRender
        rowSelection={{ getCheckboxProps: () => ({ disabled: dictProperty !== '1' }) }}
        paging={false}
        extraParams={{ dictType }}
        header={{
          headerTitle: dictName || '字典项列表',
          headerToolsRender: true,
          headerButtonList: [
            {
              key: 'back',
              ghost: true,
              type: 'primary',
              label: '返回',
              icon: <RollbackOutlined />,
            },
            {
              key: 'add',
              type: 'primary',
              disabled: dictProperty !== '1',
              label: '新增',
              icon: <PlusOutlined />,
            },
            {
              key: 'delete',
              danger: true,
              type: 'primary',
              label: '批量删除',
              loading: deleteLoading,
              disabled: dictProperty !== '1',
              confirmText: '确认批量删除所勾选的字典项数据?',
              icon: <DeleteOutlined />,
            },
          ],
          headerButtonClick: async ({ key }) => {
            switch (key) {
              case 'back':
                history.goBack();
                break;
              case 'add':
                setDictItemModalOptions({ dictType, dictName });
                setDictItemModalVisible(true);
                break;
              case 'delete':
                const { refresh, getSelectedList } = childTableRef.current;
                if (getSelectedList) {
                  const selectedList = getSelectedList();
                  if (selectedList && selectedList.length) {
                    setDeleteLoading(true);
                    try {
                      await deleteDictItemsByIds({ ids: _.map(selectedList, 'id') });
                      refresh && refresh();
                      message.success('字典项数据批量删除成功');
                    } catch (e) {
                      console.log('删除失败');
                    }
                    setDeleteLoading(false);
                  } else {
                    message.warning('请至少选择一项数据后再操作');
                  }
                }
                break;
            }
          },
        }}
        request={async (params) => {
          const records = await fetchDictChildList(params);
          return { data: records };
        }}
        columns={[
          {
            title: '字典名称',
            dataIndex: 'dictLabel',
            columnControl: { typeList: 'search' },
          },
          { title: '字典编码', dataIndex: 'dictValue', columnControl: { typeList: 'search' } },
          {
            title: '字典状态',
            dataIndex: 'dictStatus',
            columnControl: { typeList: 'filter', filterDictType: 'dict_status' },
          },
          {
            title: '操作',
            dataIndex: 'id',
            width: 160,
            render: (text, data) => {
              const deleteLoading = _.includes(deleteLoadingIds, text);
              return (
                <>
                  <DebounceButton
                    type="link"
                    size="small"
                    icon={<EditOutlined />}
                    disabled={deleteLoading || dictProperty !== '1'}
                    onClick={() => {
                      setDictItemModalOptions(data);
                      setDictItemModalVisible(true);
                    }}
                  >
                    编辑
                  </DebounceButton>
                  <Popconfirm
                    okText="确定"
                    cancelText="取消"
                    title={'确认删除该字典项，删除后不可恢复'}
                    placement="topRight"
                    onConfirm={async () => {
                      toggleDeleteLoading(text, true);
                      try {
                        await deleteDictItemById({ id: text });
                        const { refresh } = childTableRef.current;
                        refresh && refresh();
                        message.success('字典项删除成功');
                      } catch (e) {
                        console.log('删除失败');
                      }
                      toggleDeleteLoading(text, false);
                    }}
                  >
                    <DebounceButton
                      danger
                      type="link"
                      size="small"
                      icon={<DeleteOutlined />}
                      loading={deleteLoading}
                      disabled={dictProperty !== '1'}
                    >
                      删除
                    </DebounceButton>
                  </Popconfirm>
                </>
              );
            },
          },
        ]}
      />
      <DictItemDialog
        visible={dictItemModalVisible}
        options={dictItemModalOptions}
        closeModal={() => {
          setDictItemModalOptions({});
          setDictItemModalVisible(false);
        }}
        updateList={() => {
          const { refresh } = childTableRef.current;
          refresh && refresh();
        }}
      />
    </>
  );
});
